# -*- encoding: utf-8 -*-

"""
@File:      tc_libutempter_libutempter_fun001.py
@Time:      2024/2/26 10:30:20
@Author:    wangyaru
@Version:   1.0
@Contact:   wb-wyr940190@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    wangyaru
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libutempter_libutempter_fun001.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "libutempter libutempter-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >libutempter_testfile.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <utmpx.h>

int main() {
    struct utmpx *entry;
    entry = (struct utmpx *)malloc(sizeof(struct utmpx));
    if (!entry) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    // 设置utmp记录的字段值
    entry->ut_type = USER_PROCESS;
    strncpy(entry->ut_user, "libutempter_test", sizeof(entry->ut_user)-1);
    strncpy(entry->ut_line, "/dev/tty1/", sizeof(entry->ut_line));
    entry->ut_tv.tv_sec = time(NULL);
    entry->ut_tv.tv_usec = 0;

    // 将utmp记录写入到utmp文件中
    setutxent();
    pututxline(entry);
    endutxent();

    free(entry);

    return EXIT_SUCCESS;
}
EOF'''
        self.cmd(cmdline)
         
        cmdline = '''cat >libutempter_testfile_clean.c <<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <utmpx.h>

int main() {
    struct utmpx *entry;
    entry = (struct utmpx *)malloc(sizeof(struct utmpx));
    if (!entry) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    entry->ut_type = DEAD_PROCESS;
    strncpy(entry->ut_user, "libutempter_test", sizeof(entry->ut_user)-1);
    strncpy(entry->ut_line, "/dev/tty1/", sizeof(entry->ut_line));
    entry->ut_tv.tv_sec = time(NULL);
    entry->ut_tv.tv_usec = 0;

    setutxent();
    pututxline(entry);
    endutxent();

    free(entry);
}
EOF'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o libutempter_testfile libutempter_testfile.c -lutempter")
        self.cmd("./libutempter_testfile")
        code,result = self.cmd("who")
        self.assertIn("libutempter_test", result)
        code,result = self.cmd("strings /var/run/utmp")
        self.assertIn("libutempter_test", result)
        self.cmd("gcc -o libutempter_testfile_clean libutempter_testfile_clean.c -lutempter")
        self.cmd("./libutempter_testfile_clean")
        code,result = self.cmd("who")
        self.assertNotIn("libutempter_test", result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("echo ' '>/var/run/utmp")
        self.cmd("echo ' '>/var/log/wtmp")
        self.cmd("rm -rf libutempter_testfile*")